package com.example.demo.contoller;

import com.example.demo.model.JsonData;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.time.Duration;
import java.util.Arrays;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * redis + lua
 *  分布式锁
 *
 */
@RestController
@RequestMapping("/api/lock")
public class CouponController {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 获取分布式锁
     * @param couponId 锁id
     * @return 通用响应
     */
    @GetMapping("/add")
    public JsonData getLock(@RequestParam(value = "coupon_id") String couponId){
        //区分唯一锁
        String uuid = UUID.randomUUID().toString();
        //redis中key
        String key = "user:service:" + couponId;
        addLock(uuid,key);
        return JsonData.buildSuccess();
    }

    /**
     * 通过lua脚本 与redis实现分布式锁
     *  主要保证 设置key与过期时间为原子操作
     *  释放锁时校验当前锁用户与删除key保证原子性
     * @param uuid
     * @param key
     */
    private void addLock(String uuid,String key){
        long id = Thread.currentThread().getId();
        //通过原子操作进行key与过期时间得设置 返回true代表成功
        Boolean addLockResult = stringRedisTemplate.opsForValue().setIfAbsent(key, uuid, Duration.ofSeconds(30));
        if(addLockResult){
            System.out.println(id + "加锁成功");
            try{
                //业务逻辑
                TimeUnit.MILLISECONDS.sleep(10000);
            }catch(Exception e){
                e.printStackTrace();
            }finally{
                //lua脚本 校验传入的key与值是否相等，相等就删除key 释放锁
                String redisScript = "if redis.call('get',KEYS[1]) == ARGV[1] then return redis.call('del',KEYS[1]) else return 0 end";
                Long result = stringRedisTemplate.execute(new DefaultRedisScript<>(redisScript, Long.class), Arrays.asList(key), uuid);
                System.out.println(id +"解锁结果：" + result);
            }
        }else{
            //自旋操作
            System.out.println(id + "加锁失败");
            try{
                TimeUnit.SECONDS.sleep(5);
            }catch(Exception e){
                   e.printStackTrace();
            }
            addLock(uuid,key);
        }
    }
}
